package com.mk.controller;

import com.mk.client.MyMQTTClient;
import com.mk.mqtt.MqttMsg;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;



import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;


@RestController
@RequestMapping("/mqtt")
public class MqttController {

    @Autowired
    private MyMQTTClient myMQTTClient;

//    @Autowired
//    private MqttClient mqttClient;

    // 声明一次即可，不要重复 new
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Value("${mqtt.topic1}")
    String topic1;
    @Value("${mqtt.topic2}")
    String topic2;


    Queue<String> msgQueue = new LinkedList<>();
    int count = 1;

    @PostMapping("/getMsg")
    @ResponseBody
    public synchronized void mqttMsg(MqttMsg mqttMsg) {
        System.out.println("队列元素数量：" + msgQueue.size());
        System.out.println("***************" + mqttMsg.getName() + ":" + mqttMsg.getContent() + "****************");

        //时间格式化
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        mqttMsg.setTime(time);

        mqttMsg.setContent(mqttMsg.getContent() + "——后台编号：" + count);
        count++;

        // map转json（使用 Jackson）
        String sendMsg = convertMapToJson(mqttMsg);
        System.out.println(sendMsg);


        //队列添加元素
        boolean flag = msgQueue.offer(sendMsg);
        if (flag) {
            //发布消息  topic2 是你要发送到那个通道里面的主题 比如我要发送到topic2主题消息
            myMQTTClient.publish(msgQueue.poll(), topic2);
            //mqttClient.publish(msgQueue.poll(), topic2);
            System.out.println("时间戳" + System.currentTimeMillis());
        }
        System.out.println("队列元素数量：" + msgQueue.size());
    }

    private static String convertMapToJson(MqttMsg mqttMsg) {
        if (mqttMsg == null) {
            return "{}"; // 返回空对象避免 NPE
        }
        try {
            return objectMapper.writeValueAsString(mqttMsg);
        } catch (Exception e) {
            // 记录日志并处理异常
            System.err.println("JSON 转换失败: " + e.getMessage());
            return "{}";
        }
    }
}
